package com.yny.administrator.android1607_meishi.avtivity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.yny.administrator.android1607_meishi.R;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.SaveListener;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText mPhone;
    private EditText mPsd;
    private Button mLogin;
    private BmobUser mUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_login);
        initView();
        //初始化bmob对象
        Bmob.initialize(this, "88136fb03a4803b0213be8903cc26b72");
        //利用bmonuser进行用户的登陆
        mUser = new BmobUser();
        mLogin.setOnClickListener(this);
    }

    /**
     * 获取控件
     */
    private void initView() {
        mPhone = (EditText) findViewById(R.id._phone);
        mPsd = (EditText) findViewById(R.id._password);
        mLogin = (Button) findViewById(R.id.login);
    }

    /**
     * @param v 监听点击事件
     */
    @Override
    public void onClick(View v) {

        final String phoneNum = mPhone.getText().toString().trim();
        final String psd = mPsd.getText().toString().trim();
        // 非空验证
        if (TextUtils.isEmpty(phoneNum) || TextUtils.isEmpty(psd)) {
            Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        //验证用户名及密码
        mUser.setUsername(phoneNum);
        mUser.setPassword(psd);
        //利用login方法实现bmob端的登陆
        mUser.login(this, new SaveListener() {
            @Override
            public void onSuccess() {
                Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
            }

            @Override
            public void onFailure(int i, String s) {
                Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
